<template>
  <div class="query-form">
    <!-- 快捷请求输入框 -->
    <el-form :model="form" :inline="true">
      <el-row :gutter="10">
        <el-col :span="isShowSaveInterfaceBtn ? 20 : 22">
          <el-input v-model="form.url" placeholder="请输入带有http的完整URL 或 选择环境,输入接口路径，'/'开始" class="input-with-select"
            @change="changeInput" @keyup.enter="onSubmit">
            <template #prepend>
              <!-- <el-select v-model="form.protocal" @change="changeInput">
                <el-option label="http" value="http" />
                <el-option label="https" value="https" />
              </el-select> -->
              <el-select v-model="form.requestType" @change="changeInput">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
              </el-select>
              <!-- <span v-show="environmentId" class="service">{{ service['默认服务'] }}</span> -->
            </template>
          </el-input>
        </el-col>
        <el-col :span="isShowSaveInterfaceBtn ? 4 : 2">
          <el-button type="primary" @click="onSubmit">调试</el-button>
          <el-button @click="onSave" v-show="isShowSaveInterfaceBtn" type="primary" plain>保存接口</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useDebugStore } from '@/store/modules/debug'
import { getServiceURL } from '@/api/environment'
import { propTypes } from '@/utils/propTypes'
const debugStore = useDebugStore()
const environmentId = computed(() => debugStore.getEnvironmentId)
const message = useMessage() // 消息弹窗
const emit = defineEmits(['save', 'debug', 'formValue', 'paramsValue'])
const form = reactive({
  protocal: 'http',
  requestType: 'GET',
  url: '',
  params: []
})
const props = defineProps({
  data: propTypes.object.def({})
})
const service = ref([] as any) // 环境服务列表
const btnIsDisabled = ref(false) // 调试等按钮是否可用
const isShowSaveInterfaceBtn = inject('isShowSaveInterfaceBtn') // 是否展示保存接口按钮
watch(
  () => environmentId.value,
  async () => {
    await getService()
    changeInput()
  }
)
function getAllParameters(url) {
  var searchParams = new URLSearchParams(new URL(url).search);
  var params = [];
  for (let p of searchParams.entries()) {
    params.push({
      keyName: p[0],
      keyValue: p[1],
      keyType: 'string',
      enable: false,
      keyDesc: ""
    })
    // params[p[0]] = p[1];
  }
  return params;
}
/** 向上传递form值 */
const changeInput = () => {
  btnIsDisabled.value = false
  if (form.url.indexOf('=') != -1) {
    form.params = getAllParameters(form.url)
    emit('paramsValue', form)
  }
  if (form.url.indexOf('http') != -1) {
    btnIsDisabled.value = false
    form.url = form.url.trim()
    emit('formValue', form)
  } else {
    if (!environmentId.value) {
      btnIsDisabled.value = true
      // return
    }
    const envUrl = service.value[0]?.conditionUrl?.trim() || ''
    if (!envUrl && environmentId.value) {
      message.warning('该环境服务地址为空，请前往进行配置！')
      btnIsDisabled.value = true
      // return
    }
    let url = envUrl + form.url?.trim()
    emit('formValue', { ...form, url: url.replace(/([^:]\/)\/+/g, '$1') })
  }
}
/** 调试 */
const onSubmit = () => {
  if (!form.url) {
    message.warning('请输入请求地址！')
    return
  }
  if (btnIsDisabled.value) {
    message.warning('请选择环境！')
    return
  }
  emit('debug')
}
/** 保存接口 */
const onSave = () => {
  if (!form.url) {
    message.warning('请输入请求地址')
    return
  }
  emit('save')
}
/** 获取服务 */
const getService = async () => {
  const res = await getServiceURL({ systemEnvId: environmentId.value })
  service.value = res
}
const init = () => {
  if (props.data?.query?.url) {
    form.protocal = props.data.query.protocal
    form.requestType = props.data.query.requestType
    form.url = props.data.query.url
    emit('formValue', form)
  }
}
onMounted(async () => {
  init()
  if (!service.value.length && environmentId.value) {
    await getService()
    changeInput()
  }
})
</script>

<style scoped lang="scss">
:deep(.el-input-group__prepend) {
  padding: 0;

  .service {
    padding: 0 10px;
  }

  .el-select {
    width: 120px;
    margin: 0;
  }
}
</style>
